package com.huishu.file.utils;

import com.alibaba.fastjson.JSONObject;
import com.huishu.file.vo.UploadVO;
import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;


public class GoFastdfsUtils {

    private final static String UPLOAD_PATH = "http://www.poolpower.cc/group1/upload";

    private final static String VISIT_PATH = "https://www.poolpower.cc";

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public static UploadVO upload(MultipartFile file) {
        try {
            OkHttpClient httpClient = new OkHttpClient();
            MultipartBody multipartBody = new MultipartBody.Builder().
                    setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getOriginalFilename(),
                            RequestBody.create(MediaType.parse("multipart/form-data;charset=utf-8"),
                                    file.getBytes()))
                    .addFormDataPart("output", "json")
                    .build();

            Request request = new Request.Builder()
                    .url(UPLOAD_PATH)
                    .post(multipartBody)
                    .build();

            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                ResponseBody body = response.body();
                if (body != null) {
                    JSONObject object = JSONObject.parseObject(body.string());
                    return new UploadVO(VISIT_PATH + object.getString("path"), "success");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
